package com.three.message.item;

import com.google.protobuf.InvalidProtocolBufferException;
import com.three.api.connection.Connection;
import com.three.api.protocol.Packet;
import com.three.common.message.base.BaseMessage;
import com.three.domain.item.ItemPo;
import com.three.protocol.CommandEnum;
import com.three.protocol.ItemModule;
import com.three.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mathua on 2017/7/18.
 */
public final class GetPackItemsRespMessage extends BaseMessage {

    private List<ItemPo> items = new ArrayList<>();

    public GetPackItemsRespMessage(Packet packet, Connection connection) {
        super(packet, connection);
    }

    public static GetPackItemsRespMessage from(BaseMessage src) {
        return new GetPackItemsRespMessage(src.getPacket().response(CommandEnum.Command.GET_PACK_ITEMS), src.getConnection());
    }

    @Override
    public void decode(byte[] body) throws InvalidProtocolBufferException {
        ItemModule.GetPacketItemsResp_500 bodyData = ItemModule.GetPacketItemsResp_500.parseFrom(body);
        for(ItemModule.PackItem packItem : bodyData.getPackItemsList()) {
            items.add(ItemPo.buildTmp(packItem.getId(), packItem.getItemId(), packItem.getExpire(), packItem.getCount()));
        }
    }

    @Override
    public byte[] encode() {
        ItemModule.GetPacketItemsResp_500.Builder builder = ItemModule.GetPacketItemsResp_500.newBuilder();
        for(ItemPo itemPo : items) {
            builder.addPackItems(ItemModule.PackItem.newBuilder().setId(itemPo.getEntityId()).setItemId(itemPo.getItemId()).setCount(itemPo.getCount()).setExpire(itemPo.getExpire()));
        }
        return builder.build().toByteArray();
    }

    @Override
    public String toString() {
        return JsonUtils.toJson(this);
    }

    public GetPackItemsRespMessage setItems(List<ItemPo> items) {
        this.items = items;
        return this;
    }
}
